﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Yeap.Config;
using Yeap.Controllers.Filters;
using Yeap.Kernel.Security;
using Yeap.Kernel.Storage;
using Yeap.Kernel.Unity;
using Yeap.Models;

namespace Yeap.Controllers
{
    [AuthenticationFilter(false)]
    public class AccountController : Controller
    {
        public ActionResult Login()
        {
            string returnUrl = Request.Params[Constants.HtmlParameters.ReturnUrl];

            if (String.IsNullOrEmpty(returnUrl))
            {
                returnUrl = Url.Action("Index", "Home");
            }

            if (LoginUtils.CurrentUserAccount.IsLogged)
            {
                return Redirect(returnUrl);
            }

            var model = new LoginModel
                            {
                                ReturnUrl = returnUrl
                            };


            return View("Login", "_LoginLayout", model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(FormCollection form)
        {
            string login = form[Constants.HtmlParameters.LoginString];
            string password = form[Constants.HtmlParameters.Password];
            string returnUrl = form[Constants.HtmlParameters.ReturnUrl];

            var model = new LoginModel
            {
                Login = form[Constants.HtmlParameters.LoginString],
                Password = form[Constants.HtmlParameters.Password],
                ReturnUrl = returnUrl
            };

            IUser test = Global.Resolve<IUserRepository>().ReadByLogin(login);

            if (test == null)
            {
                ModelState.AddModelError("Login", "Unknown login");
                return View("Login", "_LoginLayout", model);
            }

            var passwordIsValid = HashEngine.IsValid(password, test.Password, test.Salt);

            if (!passwordIsValid)
            {
                ModelState.AddModelError("Password", "Wrong password");
                return View("Login", "_LoginLayout", model);
            }
             
            LoginUtils.SignIn(test, false);
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Logout()
        {
            LoginUtils.SignOut(HttpContext);
            return RedirectToAction("Login");
        }
    }
}
